const BaseController = require('./base_controller.js');
const DeviceControlService = require('../service/device_control_service.js');

class DeviceControlController extends BaseController {

  /**
   * 控制设备启停
   */
  async controlDevice() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
      action: 'required|string|in:start,stop|name=控制动作',
      duration: 'int|min:1|max:1440|name=使用时长(分钟)',
      orderId: 'string|name=关联订单ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new DeviceControlService();
      const result = await service.controlDevice(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 控制门禁开关
   */
  async controlDoorLock() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      doorLockId: 'required|string|name=门禁ID',
      action: 'required|string|in:open,close|name=控制动作',
      userId: 'string|name=操作用户ID',
      reason: 'string|max:100|name=操作原因',
    };

    let input = this.validateData(rules);

    try {
      const service = new DeviceControlService();
      const result = await service.controlDoorLock(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 获取设备状态
   */
  async getDeviceStatus() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new DeviceControlService();
      const result = await service.getDeviceStatus(input.deviceId);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }
}

module.exports = DeviceControlController;
